var db = require('../../config/db')
//查询
exports.search = (req,res)=>{
  if(req.query.tar =='1'){
    //用户
    db.query(`select * from land_resource where userid=?`, req.query.id, (err, results) => {
      if (err) return res.cc('500', err);
      if (results.length < 1) {
        return res.cc('404', '记录为空');
      }
      let count = 0;
      let finalResults = [];
      results.forEach((item, index) => {
        db.query('select * from land_parcel where landresourceid=?', item.id, (err, result) => {
          if (err) {
            return res.cc('500', err);
          }
          result.forEach((item1, index1) => {
            item1.address = results[index].address;
          });
          finalResults.push(...result);
          count++;
          if (count === results.length) {
            // 所有异步操作完成后，返回结果给前端
            res.send({
              status: 200,
              message: '查询成功',
              data: finalResults,
            });
          }
        });
      });
    });
  }else{//管理员
    var sql = `select * from land_parcel`
    db.query(sql, (err, results) => {
        if (err) {
          return res.cc('500', err);
        }
        if (results.length < 1) {
          return res.cc('404', '记录为空');
        }
        let count = 0;
        for (let i = 0; i < results.length; i++) {
          db.query('select * from land_resource where id=?', results[i].landresourceid, (err, result) => {
            if (err) {
              return res.cc('500', err);
            }
            results[i].address = result[0].address;
      
            db.query('select * from user_info where id=?', result[0].userid, (err, resul) => {
              if (err) {
                return res.cc('500', err);
              }
              results[i].name = resul[0].name;
              results[i].phone = resul[0].phone;
      
              count++;
              if (count === results.length) {
                // 所有异步操作完成后，返回结果给前端
                res.send({
                  status: 200,
                  message: '查询成功',
                  data: results,
                });
              }
            });
          });
        }
      });
  }
    
}
//添加
exports.add = (req,res)=>{
  
    var landParcelMes = req.body 
    if(landParcelMes.tar == '1'){
      //用户
      db.query(`select * from land_resource where name=? and userid=?`, [landParcelMes.name,landParcelMes.userid], (err, result)=>{
        //
        if(err) return res.cc('404', err.message)
        if(result.length< 1) return res.cc('404', '添加失败，您无该土地资源信息')
          
        landParcelMes.landresourceid = result[0].id
        //console.log(landParcelMes.landresourceid)
        db.query('select count(*) as count from land_parcel where landresourceid=?', landParcelMes.landresourceid, (err, result1)=>{
          const count = result1[0].count;
          db.query('select * from land_parcel where `order`=? and `landresourceid`=?', [landParcelMes.order,landParcelMes.landresourceid], (err, result2)=>{
            
            if(result2.length< 1) {//不存在编号地块冲突
              if(count < result[0].parcelcount){
                if(result[0].parcelcount<landParcelMes.order){
                  res.send({status: '404', message: '添加失败，您拥有该土地资源，不存在该地块编号'})
                }else{
                  landParcelMes.status = '空闲'
                  var sql = 'insert into land_parcel set ?'
                  const { name,id,userid,tar, ...rest } = landParcelMes;
                  db.query(sql, rest, (err, results)=>{
                      if(err) return res.cc('404', err.message)
                      if(results.affectedRows !== 1) return res.cc('404', '添加失败，请稍后再试')
                      res.send({status: 200, message: '添加成功'})
                  })

                }
                
              }
              else{
                res.send({status: 404, message: '添加的所属土地资源土地块数已满'})
              }
            }
            else{
              res.send({status: 404, message: '添加的所属土地资源土地块编号已存在'})
            }
          })
        })  
        
      })

    }else{
      db.query(`select * from land_resource where name=?`, landParcelMes.name, (err, result)=>{
        if(err) return res.cc('404', err.message)
        if(result.length< 1) return res.cc('404', '无所属土地资源存在')
        landParcelMes.landresourceid = result[0].id
        //编号地块不能超过parcelcount
        db.query('select count(*) as count from land_parcel where landresourceid=?', landParcelMes.landresourceid, (err, result1)=>{
          const count = result1[0].count;
          db.query('select * from land_parcel where `order`=?', landParcelMes.order, (err, result2)=>{
            if(result2.length< 1) {//不存在编号地块冲突
              if(count < result[0].parcelcount){
                if(result[0].parcelcount<landParcelMes.order){
                  res.send({status: '404', message: '添加失败，您拥有该土地资源，不存在该地块编号'})
                }
                landParcelMes.status = '空闲'
                var sql = 'insert into land_parcel set ?'
                const { name,id, ...rest } = landParcelMes;
                db.query(sql, rest, (err, results)=>{
                    if(err) return res.cc('404', err.message)
                    if(results.affectedRows !== 1) return res.cc('404', '添加失败，请稍后再试')
                    res.send({status: 200, message: '添加成功'})
                })
              }
              else{
                res.send({status: 404, message: '添加的所属土地资源土地块数已满'})
              }
            }
            else{
              res.send({status: 404, message: '添加的所属土地资源土地块编号已存在'})
            }
          })
        })
    })

    }
    
} 
//更新
exports.up = (req, res)=>{
  if(req.body.tar == '1'){
    //用户
    db.query('select * from land_parcel where id =?', req.body.id, (err, results)=>{
      if(results[0].order == req.body.order) {//没有改order的情况
          //req.body.status = '空闲'
        db.query('update land_parcel set area=?, type=?, ph=?, nutrient=?, irrigationfacility=?, light=? WHERE id=?', [req.body.area, req.body.type, req.body.ph, req.body.nutrient, req.body.irrigationfacility, req.body.light, req.body.id], (err, results1)=>{
        if(err) return res.cc('404',err)
        if(results1.affectedRows !== 1) return res.cc('500','修改失败')
        res.send({ //返回前端信息
            status: 200,
            message: '修改成功',
        })
        })
      }
      else{//改的情况
        db.query('SELECT * FROM land_resource WHERE id = ?', req.body.landresourceid, (err, result2) => {
          if (err) {
            console.error('查询出错:', err);
            res.send({ status: 500, message: '查询出错' });
          }
          if(result2[0].parcelcount< req.body.order){//是否超出范围
            res.send({status: 404, message: '修改失败:修改的土地块编号不存在'})
          }
          else{//
            db.query('SELECT * FROM land_parcel WHERE landresourceid = ? AND `order` = ?', [req.body.landresourceid, req.body.order], (err, result3) => {
              if (err) {
                console.error('查询出错:', err);
                res.send({ status: 500, message: '查询出错' });
              }
              if (result3.length > 0 && result3[0].order == req.body.order) {
                res.send({ status: 404, message: '修改失败:修改的所属土地资源土地块编号已存在' });
              }
              else{
                //req.body.status = '空闲'
                db.query('update land_parcel set area=?, type=?, ph=?, nutrient=?, irrigationfacility=?, light=?, `order`=? WHERE id=?', [req.body.area, req.body.type, req.body.ph, req.body.nutrient, req.body.irrigationfacility, req.body.light, req.body.order, req.body.id], (err, result4)=>{
                  if(err) return res.cc('404',err)
                  if(result4.affectedRows !== 1) return res.cc('500','修改失败')
                  res.send({ //返回前端信息
                      status: 200,
                      message: '修改成功',
                  })
                })
              }
            }); 
          } 
        });
      }
    })
  }else{
    db.query('select * from land_parcel where id =?', req.body.id, (err, results)=>{
      if(results[0].order == req.body.order) {//没有改order的情况
          //req.body.status = '空闲'
        db.query('update land_parcel set area=?, type=?, ph=?, nutrient=?, irrigationfacility=?, light=? WHERE id=?', [req.body.area, req.body.type, req.body.ph, req.body.nutrient, req.body.irrigationfacility, req.body.light, req.body.id], (err, results1)=>{
        if(err) return res.cc('404',err)
        if(results1.affectedRows !== 1) return res.cc('500','修改失败')
        res.send({ //返回前端信息
            status: 200,
            message: '修改成功',
        })
        })
      }
      else{//改的情况
        db.query('SELECT * FROM land_resource WHERE id = ?', req.body.landresourceid, (err, result2) => {
          if (err) {
            console.error('查询出错:', err);
            res.send({ status: 500, message: '查询出错' });
          }
          if(result2[0].parcelcount< req.body.order){//是否超出范围
            res.send({status: 404, message: '修改失败:修改的土地块编号不存在'})
          }
          else{//
            db.query('SELECT * FROM land_parcel WHERE landresourceid = ? AND `order` = ?', [req.body.landresourceid, req.body.order], (err, result3) => {
              if (err) {
                console.error('查询出错:', err);
                res.send({ status: 500, message: '查询出错' });
              }
              if (result3.length > 0 && result3[0].order == req.body.order) {
                res.send({ status: 404, message: '修改失败:修改的所属土地资源土地块编号已存在' });
              }
              else{
                //req.body.status = '空闲'
                db.query('update land_parcel set area=?, type=?, ph=?, nutrient=?, irrigationfacility=?, light=?, `order`=? WHERE id=?', [req.body.area, req.body.type, req.body.ph, req.body.nutrient, req.body.irrigationfacility, req.body.light, req.body.order, req.body.id], (err, result4)=>{
                  if(err) return res.cc('404',err)
                  if(result4.affectedRows !== 1) return res.cc('500','修改失败')
                  res.send({ //返回前端信息
                      status: 200,
                      message: '修改成功',
                  })
                })
              }
            }); 
          } 
        });
      }
    })
  }
}
//删除
exports.delete = (req,res)=>{
  db.query('select * from vegetable_plot where landparcelid=?', req.query.id, (err, results) => {
    //
    if(err) return res.cc('404', err.message)
    if(results.length< 1){
      db.query('DELETE FROM land_parcel WHERE id = ?', req.query.id, (err, results1)=>{
        if(err) return res.cc('404', err.message)
        if(results1.affectedRows !== 1) return res.cc('500', '删除失败');
        res.send({status: 200, message: '删除成功'})
    })
    }
    else{
      res.send({status: '404', message: '删除失败，存在关联的菜地种植信息，请先删除'})
    }
  })
}